package se.ytterman.jpcap.data;

import java.lang.*;
import java.io.*;
import java.util.*;
import java.util.regex.*;

public abstract class BinaryData {
    // prepare
    public void begin(InputStream packetDataStream) throws Exception {
	// Check if data is available...
	if(this.payload_length > packetDataStream.available()) {
	    // XXX Throw exception
	}
	
	// Check if this stream support marking and mark stream position
	if(packetDataStream.markSupported()) {
	    // Set readahead limit to buffer length and mark
	    packetDataStream.mark(this.payload_length);
	}
	else {
	    // XXX Throw exception
	}
    }

    // read
    public abstract void read(InputStream packetDataStream) throws Exception;

    // write
    public abstract void write(OutputStream packetDataStream) throws Exception; 

    // commit
    public void commit(InputStream packetDataStream) throws Exception {
	// Check if this stream support marking and reset stream position
	if(packetDataStream.markSupported()) {
	    // Set readahead limit to zero and mark, thus discarding the 
	    // possibility of rollback
	    packetDataStream.mark(0);
	}
	else {
	    // XXX Throw exception
	}
    }

    // rollback
    public void rollback(InputStream packetDataStream) throws Exception {
	// Check if this stream support marking and reset stream position
	if(packetDataStream.markSupported()) {
	    // Move stream pointer to previously made mark
	    packetDataStream.reset();
	}
	else {
	    // XXX Throw exception
	}
    }

    // toString
    public abstract String toString();

    // Length of payload in bytes
    protected int payload_length = 0;
}
